import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '@views/Home'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home',
    meta: {
      needLogin: false

    }
  },
  {
    path: '/home',
    name: '首页',
    component: Home,
    meta: {
      needLogin: false,
      keepAlive: true,
      deep: 2
    }
  },
  {
    path: '/cate',
    name: '分类',
    component: () => import('@views/Cate'),
    meta: {
      needLogin: false,
      keepAlive: true
    }
  },
  {
    path: '/cart',
    name: '购物车',
    component: () => import('@views/Cart'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/user',
    name: '个人中心',
    component: () => import('@views/User'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/itemLists/:cate_id',
    name: '商品列表',
    component: () => import('@views/ItemLists'),
    meta: {
      needLogin: false,
      keepAlive: true,
      deep: 1
    }
  },
  {
    path: '/detail',
    name: '商品详情',
    component: () => import('@views/Detail'),
    meta: {
      needLogin: false,
      deep: 0.5
    }
  },
  {
    path: '/login',
    name: '登录',
    component: () => import('@views/Login'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/order',
    name: '确认订单',
    component: () => import('@views/Order'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactLists',
    name: '联系人列表',
    component: () => import('@views/ContactLists'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactAdd',
    name: '添加联系人',
    component: () => import('@views/ContactAdd'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/contactEdit',
    name: '编辑联系人',
    component: () => import('@views/ContactEdit'),
    meta: {
      needLogin: true
    }
  },
  {
    path: '/search',
    name: '搜索',
    component: () => import('@views/Search'),
    meta: {
      needLogin: false
    }
  },
  {
    path: '/searchResult',
    name: '搜索结果',
    component: () => import('@views/SearchResult'),
    meta: {
      needLogin: false
    }
  }
]

const router = new VueRouter({
  mode: 'hash',
  base: process.env.BASE_URL,
  routes
})
router.beforeEach((to, from, next) => {
  // 判断哪些路由需要登录 需要登录 判断是否登录
  if (to.meta.needLogin) {
    // 需要登录权限
    // 判断是否登录
    const token = localStorage.getItem('access_token')
    if (token) {
      // 说明登录了
      next()
    } else {
      // 没有登录 去登录
      next({
        path: '/login',
        query: {
          from: to.fullPath
        }
      })
    }
  } else {
    next()
  }
})
export default router
